package ui.login;

import java.net.MalformedURLException;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.sql.SQLException;

import javax.swing.JFrame;

import blservice.user.UserBLService;
import tool.MyButton;
import tool.MyLabel;
import tool.PasswordEncryptor;
import ui.accountor.AccountorFrame;
import ui.administrator.AdminFrame;
import ui.commodityman.CommodityManagerFrame;
import ui.importandsaleman.ImportandsaleFrame;
import ui.manager.ManagerFrame;
import vo.UserVo;
import vo.Vo;

import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JPasswordField;

import client.boot.BLServiceManager;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;

public class LoginFrame extends JFrame {
	
	private static final long serialVersionUID = -7833682539710591053L;

	private static final File settings = new File("hostip");
	private UserBLService userBL;
	private JTextField userNameTF;
	private JTextField hostIPTF;
	private JPasswordField passwordField;
	private JPasswordField newPasswordField;
	private JPasswordField newPasswordAgainField;
	private JButton btnLogin;
	private JButton btnConfirm;
	private JButton btnExit;
	private JButton btnCancle;
	private JButton btnChangePassword;
	private JLabel lblNewPassword;
	JLabel lblHostIp;
	JLabel lblPasswordAgain;

	public static void main(String[] args) {
		LoginFrame lf = new LoginFrame();
		lf.setVisible(true);
	}
    
	public LoginFrame() {
		//设置背景
		this.setContentPane(new JPanel(){
			
			private static final long serialVersionUID = -8067534092982934270L;

			@Override
			public void paint(Graphics g) {
				this.setBackground(new Color(0, 0, 0, 0));
				Image background = Toolkit.getDefaultToolkit().getImage("Graphics/login.jpg");
				g.drawImage(background, 0, 0, null);
				super.paint(g);
			}
		});
		
		
		//动画开始
		setUndecorated(true);
		this.setVisible(true);
		this.setBounds(330, 150, 0, 0);
		JLabel gif=new JLabel();
		gif.setBounds(0, 0, 562, 425);
		gif.setIcon(new ImageIcon("Graphics/login.gif"));
		getContentPane().add(gif);
		this.setSize(525,525);
		try {
			Thread.sleep(2500);
		} catch (InterruptedException e1) {
		}
		gif.setVisible(false);
		this.setVisible(false);
		//动画结束
		
		setTitle("登录");
		this.setDefaultCloseOperation(EXIT_ON_CLOSE);
		this.setBounds(200,100,850, 535);
		getContentPane().setLayout(null);
		this.setResizable(false);

		
		JLabel lblUsername = new MyLabel("用户名");
		lblUsername.setBounds(620, 155, 54, 15);
		getContentPane().add(lblUsername);

		JLabel lblPassword = new MyLabel("密码");
		lblPassword.setBounds(620, 186, 54, 15);
		getContentPane().add(lblPassword);

		userNameTF = new JTextField();
		userNameTF.setBounds(691, 152, 129, 21);
		getContentPane().add(userNameTF);
		userNameTF.setColumns(10);

		lblHostIp = new MyLabel("服务器 IP");
		lblHostIp.setBounds(620, 345, 54, 15);
		getContentPane().add(lblHostIp);

		lblPasswordAgain = new MyLabel("新密码确认");
		lblPasswordAgain.setBounds(620, 281, 66, 15);
		getContentPane().add(lblPasswordAgain);

		hostIPTF = new JTextField();
		hostIPTF.setBounds(691, 342, 129, 21);
		getContentPane().add(hostIPTF);
		hostIPTF.setColumns(10);
		loadHostIP();

		newPasswordAgainField = new JPasswordField();
		newPasswordAgainField.setBounds(691, 278, 129, 21);
		getContentPane().add(newPasswordAgainField);

		btnLogin = new MyButton("Graphics/Button88-23.png");
		btnLogin.setText("登录");
		btnLogin.addActionListener(e -> login());
		btnLogin.setBounds(620, 373, 88, 23);
		getContentPane().add(btnLogin);

		btnConfirm =new MyButton("Graphics/Button88-23.png");
		btnConfirm.setText("确定");
		btnConfirm.addActionListener(e -> changePassword());
		btnConfirm.setBounds(620, 309, 88, 23);
		getContentPane().add(btnConfirm);

		btnExit = new MyButton("Graphics/Button88-23.png");
		btnExit.setText("退出");
		btnExit.addActionListener(e -> LoginFrame.this.dispose());
		btnExit.setBounds(732, 373, 88, 23);
		getContentPane().add(btnExit);

		btnCancle =new MyButton("Graphics/Button88-23.png");
		btnCancle.setText("取消");
		btnCancle.addActionListener(e -> toLogin());
		btnCancle.setBounds(732, 309, 88, 23);
		getContentPane().add(btnCancle);

		passwordField = new JPasswordField();
		passwordField.setBounds(691, 183, 129, 21);
		getContentPane().add(passwordField);

		newPasswordField = new JPasswordField();
		newPasswordField.setBounds(691, 247, 129, 21);
		getContentPane().add(newPasswordField);

		lblNewPassword = new MyLabel("新密码");
		lblNewPassword.setBounds(620, 250, 54, 15);
		getContentPane().add(lblNewPassword);

		btnChangePassword = new MyButton("Graphics/Button88-23.png");
		btnChangePassword.setText("修改密码");
		btnChangePassword.addActionListener(e -> toChangePassword());
		btnChangePassword.setBounds(732, 214, 88, 23);
		getContentPane().add(btnChangePassword);
		
		
		
		toLogin();
	}

	private void login() {
		saveHostIP();
		try {
			iniBLServiceManager();
			userBL = BLServiceManager.getUserBLService();
			PasswordEncryptor pe = new PasswordEncryptor();
			@SuppressWarnings("deprecation")
			String password = pe.encrypt(passwordField.getText());
			UserVo user = new UserVo();
			user.setName(userNameTF.getText());
			user.setPassword(password);
			try {
				user = userBL.checkLogin(user);
				if (user.isSuccessed()) {
					switch (user.getUserType()) {
					case 库存管理人员:
						CommodityManagerFrame cmf = new CommodityManagerFrame(
								user);
						cmf.setVisible(true);
						this.dispose();
						break;
					case 总经理:
						ManagerFrame mf = new ManagerFrame(user);
						mf.setVisible(true);
						this.dispose();
						break;
					case 管理员:
						AdminFrame admf = new AdminFrame(user);
						admf.setVisible(true);
						this.dispose();
						break;
					case 财务人员:
						AccountorFrame af = new AccountorFrame(user);
						af.setVisible(true);
						this.dispose();
						break;
					case 进货销售人员:
						ImportandsaleFrame itsf = new ImportandsaleFrame(user);
						itsf.setVisible(true);
						this.dispose();
						break;
					}
				} else {
					JOptionPane.showMessageDialog(this, user.getFailMessage()
							+ "，登录失败\n");
				}
			} catch (RemoteException e) {
				JOptionPane.showMessageDialog(this,
						"无法连接到服务器，登录失败\n" + e.getMessage());
				e.printStackTrace();
			}
		} catch (RemoteException | MalformedURLException | NotBoundException e1) {
			JOptionPane.showMessageDialog(this,
					"无法连接到服务器，登录失败\n" + e1.getMessage());
			e1.printStackTrace();
		} catch (SQLException e2) {
			JOptionPane.showMessageDialog(this,
					"无法连接到数据库，登录失败\n" + e2.getMessage());
			e2.printStackTrace();
		}

	}

	private void toLogin() {
		btnLogin.setVisible(true);
		btnConfirm.setVisible(false);
		btnExit.setVisible(true);
		btnCancle.setVisible(false);
		btnChangePassword.setVisible(true);
		lblNewPassword.setVisible(false);
		newPasswordField.setVisible(false);
		lblPasswordAgain.setVisible(false);
		newPasswordAgainField.setVisible(false);
		hostIPTF.setVisible(true);
		lblHostIp.setVisible(true);
	}

	private void toChangePassword() {
		btnLogin.setVisible(false);
		btnConfirm.setVisible(true);
		btnExit.setVisible(false);
		btnCancle.setVisible(true);
		btnChangePassword.setVisible(false);
		lblNewPassword.setVisible(true);
		newPasswordField.setVisible(true);
		lblPasswordAgain.setVisible(true);
		newPasswordAgainField.setVisible(true);
		hostIPTF.setVisible(false);
		lblHostIp.setVisible(false);
	}

	private void changePassword() {
		boolean passwordSame = true;
		if (newPasswordField.getPassword().length == newPasswordAgainField
				.getPassword().length)
			for (int i = 0; i < newPasswordField.getPassword().length; i++) {
				if (newPasswordField.getPassword()[i] != newPasswordAgainField
						.getPassword()[i]) {
					passwordSame = false;
					break;
				}
			}
		else {
			passwordSame = false;
		}
		if (!passwordSame) {
			JOptionPane.showMessageDialog(this, "两次输入的密码不一致");
			return;
		}
		try {			
			try {
				iniBLServiceManager();
				userBL = BLServiceManager.getUserBLService();
			} catch (SQLException e1) {
				JOptionPane.showMessageDialog(this,
						"无法连接到数据库，登录失败\n" + e1.getMessage());
				e1.printStackTrace();
			}
			UserVo user = new UserVo();
			PasswordEncryptor pe = new PasswordEncryptor();
			user.setName(userNameTF.getText());
			@SuppressWarnings("deprecation")
			String password = pe.encrypt(passwordField.getText());
			@SuppressWarnings("deprecation")
			String newPassword = pe.encrypt(newPasswordField.getText());
			user.setPassword(password);
			user.setNewPassword(newPassword);
			Vo result;
			try {
				result = userBL.changePassword(user);
				if (result.isSuccessed()) {
					JOptionPane.showMessageDialog(this, "密码修改成功");
					toLogin();
					passwordField.setText("");
				} else {
					JOptionPane.showMessageDialog(this, result.getFailMessage()
							+ "，密码修改失败");
				}
			} catch (RemoteException e) {
				JOptionPane.showMessageDialog(this,
						"无法连接到服务器，登录失败\n" + e.getMessage());
				e.printStackTrace();
			}
		} catch (RemoteException | MalformedURLException | NotBoundException e1) {
			JOptionPane.showMessageDialog(this,
					"无法连接到服务器，登录失败\n" + e1.getMessage());
			e1.printStackTrace();
		}

	}

	private void loadHostIP() {
		try {
			BufferedReader br = new BufferedReader(new FileReader(settings));
			hostIPTF.setText(br.readLine());
			br.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private void saveHostIP() {
		try {
			OutputStreamWriter osw = new OutputStreamWriter(
					new FileOutputStream(settings));
			osw.write(hostIPTF.getText());
			osw.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private void iniBLServiceManager() throws MalformedURLException,
			RemoteException, NotBoundException, SQLException {
		BLServiceManager.setServerIP(hostIPTF.getText());
	}
	
	
}
